/**
 * CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

package com.cmcc.zysoft.spring.security.jxl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.AbstractView;

/**
 * @author 袁凤建
 * <br />邮箱: yuan.fengjian@ustcinfo.com
 * <br />描述: JXLSExcelView.java
 * <br />版本: 1.0.0
 * <br />日期: 2013-9-29 下午2:59:09
 * <br />CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

public class JXLSExcelView extends AbstractView {

	public static final String EXCEL_EXPORT_FILE_NAME = "ExcelExportFileName";
	
	public static final String EXCEL_TEMPLATE_FILE_NAME = "ExcelTemplateFileName";
	
	/** The content type for an Excel response */
	private static final String CONTENT_TYPE = "application/vnd.ms-excel";
	
	private static final String TEMPLATS_PATH = File.separator + "resources" + File.separator + "excel" + File.separator + "templates" + File.separator;
	
	private XLSTransformerExt transformer;
	
	/**
	 * Default Constructor.
	 * Sets the content type of the view to "application/vnd.ms-excel".
	 */
	public JXLSExcelView() {
		transformer = new XLSTransformerExt();
		setContentType(CONTENT_TYPE);
	}
	
	@Override
	protected boolean generatesDownloadContent() {
		return true;
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fileName = (String)model.get(EXCEL_EXPORT_FILE_NAME);
		String templateName = (String)model.get(EXCEL_TEMPLATE_FILE_NAME);
		String agent = request.getHeader("USER-AGENT").toLowerCase();// 判断浏览器
		// 处理导出文件名为中文乱码情况
		if (agent.indexOf("firefox") > -1) {// 浏览器为火狐
			fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
		} else {// 默认浏览器为IE，其他的浏览器皆可用 
			fileName = URLEncoder.encode(fileName, "UTF-8");
		}
		response.setHeader("content-disposition","attachment; filename="+fileName);
		
		String realPath = request.getServletContext().getRealPath("");
		realPath = realPath + TEMPLATS_PATH + templateName;
	  	ServletOutputStream out = response.getOutputStream();
	  	transformer.transformXLS(realPath, model, out);
	  	out.flush();
	}
}